import { getAPIDomain } from '../../libs/utils.js'
import { GET, POST } from '../../libs/request.js'
import { API_getUserInfo } from '../api.js'

// ------------------------------------
// Constants
// ------------------------------------
export const UPDATE_PHONE_NUMBER = 'UPDATE_PHONE_NUMBER'
export const UPDATE_AVATAR       = 'UPDATE_AVATAR'
export const GET_USER_INFO       = 'GET_USER_INFO'

// ------------------------------------
// helpers
// ------------------------------------


// ------------------------------------
// Actions
// ------------------------------------
function updatePhoneNumber(phone) {
  return {
    type: UPDATE_PHONE_NUMBER,
    payload: {
      phone
    }
  }
}

function updateAvatar(avatar) {
  return {
    type: UPDATE_AVATAR,
    payload: {
      avatar
    }
  }
}

function getUserInfo(userInfo) {
  return {
    type: GET_USER_INFO,
    payload: {
      userInfo
    }
  }
}

// ------------------------------------
// Async Actions
// ------------------------------------
export const verifyPhoneNumber = (phone, errorCallback) => {
  return (dispatch, getState) => {
    dispatch(updatePhoneNumber(phone))
  }
}

export const fetchAvatar = avatar => {
  return (dispatch, getState) => {
    dispatch(updateAvatar(avatar))
  }
}

export const fetchUserInfo = userInfo => {
  return (dispatch, getState) => {
    API_getUserInfo()
    .then(
      res => {
        const userInfo = res.data
        dispatch(getUserInfo(userInfo))
      }
    )
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [UPDATE_PHONE_NUMBER]: (personal, action) => {
    const payload = action.payload
    const phone   = payload.phone

    return Object.assign({}, personal, {
      phone
    })
  },

  [UPDATE_AVATAR]: (personal, action) => {
    const payload = action.payload
    const avatar  = payload.avatar

    return Object.assign({}, personal, {
      avatar
    })
  },

  [GET_USER_INFO]: (personal, action) => {
    const payload  = action.payload
    const {name, whatup, phone, avatar} = payload.userInfo

    return {
      name,
      phone,
      avatar,
      introduction: whatup
    }
  },
}


// ------------------------------------
// Reducer
// ------------------------------------
export function personalReducer(personal = {
  name: '',
  phone: '',
  avatar: '',
  introduction: '',
}, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(personal, action) : personal
}
